/**spring-cloud-loadbalancer+RestTemplate/WebClient
 * 1）依赖库：SpringCloud版本为2020.0.0及以上，核心依赖为spring-boot-starter-web、spring-boot-starter-webflux和spring-cloud-starter-loadbalancer
 * 2）定义RestTemplate/webClientBuilder，用@Loadbanlanced注解之（公共@configurayion文件或main文件）
 * 3）定义负载均衡策略和提供服务列表（只能在@configuratio文件或main文件中），
 * 4）可选：@@LoadBalancerClient仅在单独配置规则和无服务发现时使用，服务名小写有效（公共@configurayion文件或main文件）
 * 5）注入RestTemplate或LoadBalancerClient或webClient，用服务名称调用微服务（consummer controller文件）
 */
package com.example.demolbclientwithouteureka;

import com.example.config.ApplicationConf;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.reactive.ReactiveLoadBalancer;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClient;
import org.springframework.cloud.loadbalancer.core.RandomLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;

@SpringBootApplication
@LoadBalancerClient(name = "userlogin", configuration = ApplicationConf.class)
public class DemoLbClientWithoutEurekaApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoLbClientWithoutEurekaApplication.class, args);
    }


    @Bean
    @LoadBalanced    //启用负载均衡
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }


    @Bean
    @LoadBalanced
    WebClient.Builder webClientBuilder() {
        return WebClient.builder();
    }

    @Bean
    WebClient webClient() {
        return webClientBuilder().build();
    }


    @Bean
    public ReactiveLoadBalancer<ServiceInstance> reactorServiceInstanceLoadBalancer(Environment environment,
                                                                                    LoadBalancerClientFactory loadBalancerClientFactory) {
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        return new RandomLoadBalancer(
                loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), name);
    }

}
